//
//  MSOtherEntriesController.m
//  觅尚
//
//  Created by No.8 on 2019/4/7.
//  Copyright © 2019 No.8. All rights reserved.
//

#import "MSOtherEntriesController.h"
#import "MSActivateCardCell.h"
#import "MSOtherEntriesCell.h"
#import "MSSelectionButton.h"
#import "MSOtherEntriesModel.h"
#define pageSize 20

@interface MSOtherEntriesController ()<UITableViewDelegate,UITableViewDataSource>
//通用导航栏
{
    CustomNavigationBar *naviagtionBar;
    
    NSInteger page;
    NSInteger count;
    
}
/** 表视图*/
@property(nonatomic,strong)UITableView *tableView;

/** 表视图*/
@property(nonatomic,strong)UIView *HeaderView;


/** 取反*/
@property(nonatomic,strong)UIButton *typeButton;

/** 遮盖层*/
@property(nonatomic,strong)UIView *backView;


/** 弹出View*/
@property(nonatomic,strong)UIView *showView;

/** 取反 */
@property (nonatomic, weak) UIButton  * selectedButton;

/** 项目名称*/
@property(nonatomic,strong)UITextField *BackConsumptionStatisticsField;


/** 收入金额*/
@property(nonatomic,strong)UITextField *TotalConsumptionField;

/** 数组*/
@property(nonatomic,strong)NSMutableArray *DataArray;

/** 总计*/
@property(nonatomic,strong)UILabel *totleCountLabel;

/** 时间*/
@property(nonatomic,strong)UILabel *timeLabel;

@end

@implementation MSOtherEntriesController

/** Nav实现 */
- (int)navBarBottom {
    if ([WRNavigationBar isIphoneX]) {
        return 88;
    } else {
        return 64;
    }
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.hidden = YES;
    
    self.view.backgroundColor = backgroundcolor;
    
    self.DataArray = [NSMutableArray new];
    
    Prepare *header = [Prepare headerWithRefreshingTarget:self refreshingAction:@selector(MJChiBaoZiHeaderRefresh)];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    // 马上进入刷新状态
    self.tableView.mj_header = header;
    [self.tableView.mj_header beginRefreshing];
    
}
- (void)MJChiBaoZiHeaderRefresh{
    page = 1;
    [self ReloadData];
}
- (void)MJChiBaoZiFootderRefresh{
    if (count / pageSize < page) {
        [MBManager showBriefAlert:@"没有更多数据了"];
    }else{
        page++;
    }
    [self FootderRefreshReloadData];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    self.navigationController.navigationBar.hidden = YES;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self CreateNavigationBar];
    
    [self CreatView];
    
    [self tableView];
    
    
    PrepareFooter *footder = [PrepareFooter footerWithRefreshingTarget:self refreshingAction:@selector(MJChiBaoZiFootderRefresh)];
    // 马上进入刷新状态
    self.tableView.mj_footer = footder;
}
- (void)CreatView{
    
    UIView * HeaderView = [[UIView alloc] init];
    HeaderView.x = 0;
    HeaderView.x = 0;
    HeaderView.width = ScreenWidth;
    HeaderView.backgroundColor = backgroundcolor;
    
    //    self.CollectionHeaderView = HeaderView;
    
    /** 房间总量*/
    UILabel * totleCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(40 * px, 40 * px, ScreenWidth / 3 * 2, 60 * px)];
    totleCountLabel.textColor = [UIColor whiteColor];
    totleCountLabel.text = @"总计:￥1800";
    totleCountLabel.textAlignment = NSTextAlignmentLeft;
    totleCountLabel.font = [UIFont systemFontOfSize:SYRealValue(28 / 2)];
    [HeaderView addSubview:totleCountLabel];
    self.totleCountLabel = totleCountLabel;
    
    
    /** 时间*/
    UILabel * timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth / 2, totleCountLabel.y, ScreenWidth / 2 - 60 * px, totleCountLabel.height)];
    timeLabel.textColor = totleCountLabel.textColor;
    timeLabel.text = @"2019.04.01";
    timeLabel.font = totleCountLabel.font;
    timeLabel.textAlignment = NSTextAlignmentRight;
    [HeaderView addSubview:timeLabel];
    self.timeLabel = timeLabel;
    
    
    UIView * lineView = [[UIView alloc] init];
    lineView.frame = CGRectMake(0, CGRectGetMaxY(totleCountLabel.frame) + 40 * px, HeaderView.width, 1);
    lineView.backgroundColor = BackViewColor;
    [HeaderView addSubview:lineView];
    
    
    HeaderView.height = CGRectGetMaxY(lineView.frame);
    [self.view addSubview:HeaderView];
    self.tableView.tableHeaderView = HeaderView;
    
    
    UIButton * bottomButton = [[UIButton alloc] initWithFrame:CGRectMake(0, ScreenHeight - 150 * px, ScreenWidth, 150 * px)];
    [bottomButton setTitle:@"添加" forState:UIControlStateNormal];
    bottomButton.titleLabel.font = [UIFont systemFontOfSize:SYRealValue(28 / 2)];
    [bottomButton setBackgroundImage:[UIImage imageNamed:@"底部按钮背景"] forState:UIControlStateNormal];
    [bottomButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [bottomButton addTarget:self action:@selector(playCardButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bottomButton];
    
}
- (void)ReloadData{
    
    [MBManager showLoading];
    [self.DataArray removeAllObjects];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSDate *datenow = [NSDate date];
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    self.timeLabel.text = [NSString stringWithFormat:@"%@",currentTimeString];
    
    NSDictionary * params = @{@"busId":[WYCAccountTool unarchivebelongBusid],@"page":@(page),@"pageSize":@(pageSize)};
    [HTTPRequest POST:MSgetOtherIncome params:params succeed:^(id responseObject) {
        WYCLog(@"----------%@",responseObject);
        if (CodeStr) {
            
            count = [responseObject[@"data"][@"count"] integerValue];
            self.totleCountLabel.text = [NSString stringWithFormat:@"总计: ￥%@",responseObject[@"data"][@"sumOtherMoney"]];
            [self.tableView.mj_header endRefreshing];
            [MBManager hideAlert];
            NSMutableArray *temporaryArray = [NSMutableArray new];
            temporaryArray = [MSOtherEntriesModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"otherIncomeList"]];
            self.DataArray = temporaryArray;
        }else{
            [self.tableView.mj_header endRefreshing];
            [MBManager hideAlert];
            [MBManager showBriefAlert:responseObject[@"msg"]];
            page = [params[@"page"] integerValue];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [MBManager hideAlert];
        [MBManager showBriefAlert:Failed];
    }];
    
}
- (void)FootderRefreshReloadData{
    
    [MBManager showLoading];
    [self.DataArray removeAllObjects];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSDate *datenow = [NSDate date];
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    self.timeLabel.text = [NSString stringWithFormat:@"%@",currentTimeString];
    
    NSDictionary * params = @{@"busId":[WYCAccountTool unarchivebelongBusid],@"page":@(page),@"pageSize":@(pageSize)};
    [HTTPRequest POST:MSgetOtherIncome params:params succeed:^(id responseObject) {
        WYCLog(@"----------%@",responseObject);
        if (CodeStr) {
            
            self.totleCountLabel.text = [NSString stringWithFormat:@"总计: ￥%@",responseObject[@"data"][@"sumOtherMoney"]];
            [self.tableView.mj_footer endRefreshing];
            [MBManager hideAlert];
            self.DataArray = [MSOtherEntriesModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"otherIncomeList"]];
        }else{
            [self.tableView.mj_footer endRefreshing];
            [MBManager hideAlert];
            [MBManager showBriefAlert:responseObject[@"msg"]];
            page --;
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
        [MBManager hideAlert];
        [MBManager showBriefAlert:Failed];
    }];
}
/** 表视图*/
- (UITableView *)tableView{
    self.extendedLayoutIncludesOpaqueBars = YES;
    if (!_tableView) {
        
        if (@available(iOS 11.0, *)) {
            
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            
        } else {
            
            self.automaticallyAdjustsScrollViewInsets = NO;
            
        }
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, [self navBarBottom], ScreenWidth, ScreenHeight - [self navBarBottom] - self.tabBarController.tabBar.height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:self.tableView];
    }
    return _tableView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.DataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 140 * px;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    MSOtherEntriesCell * cell = [MSOtherEntriesCell cellWithTableView:tableView];
    tableView.backgroundColor = [UIColor clearColor];
    //    [cell.operationButton addTarget:self action:@selector(operationButtonClick) forControlEvents:UIControlEventTouchUpInside];
    //无色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.OtherEntriesModel = self.DataArray[indexPath.row];
    //    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}
- (void)CreateNavigationBar{
    
    self.view.backgroundColor = backgroundcolor;
    naviagtionBar = [[CustomNavigationBar alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, [self navBarBottom])];
    [self.view addSubview:naviagtionBar];
    naviagtionBar.titleLabel.text = @"其他入账";
    naviagtionBar.rightBtn.hidden = YES;
    naviagtionBar.rightBtnTitle.hidden = YES;
    [self.view addSubview:naviagtionBar];
    
    [naviagtionBar.leftBtn setImage:[UIImage imageNamed:@"左箭头"] forState:UIControlStateNormal];
    [naviagtionBar.leftBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    
}
- (void)backClick{
    
    [self.navigationController popViewControllerAnimated:NO];
}


//弹出
- (void)playCardButton{
    
    UIView * view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    [[UIApplication sharedApplication].keyWindow  addSubview:view];
    self.backView = view;

    
    
    UIView * showView = [[UIView alloc] init];
    showView.frame = CGRectMake(100 * px, ScreenHeight / 4, ScreenWidth - 200 * px, ScreenHeight / 3 * 2 - 200 * px);
    showView.backgroundColor = [UIColor whiteColor];
    showView.layer.cornerRadius = 20 * px;
    [view addSubview:showView];
    self.showView = showView;
    //设置所需的圆角位置以及大小
    UIBezierPath * showViewmaskPath = [UIBezierPath bezierPathWithRoundedRect:showView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer * showViewmaskLayer = [[CAShapeLayer alloc] init];
    showViewmaskLayer.frame = showView.bounds;
    showViewmaskLayer.path = showViewmaskPath.CGPath;
    showView.layer.mask = showViewmaskLayer;
    
    
    UIButton * choseButton = [[UIButton alloc] init];
    choseButton.frame = CGRectMake(showView.width - 90 * px, 20 * px, 60 * px, 60 * px);
    [choseButton setImage:[UIImage imageNamed:@"pop_dis"] forState:UIControlStateNormal];
    [choseButton addTarget:self action:@selector(choseButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [showView addSubview:choseButton];
    
    
    /** 消费统计总额*/
    UILabel * BackConsumptionStatisticsTitle = [[UILabel alloc] initWithFrame:CGRectMake(60 * px, CGRectGetMaxY(choseButton.frame) + 40 * px, showView.width / 2, 60 * px)];
    BackConsumptionStatisticsTitle.textColor = [UIColor blackColor];
    BackConsumptionStatisticsTitle.text = @"收入名称";
    BackConsumptionStatisticsTitle.textAlignment = NSTextAlignmentLeft;
    BackConsumptionStatisticsTitle.font = [UIFont systemFontOfSize:SYRealValue(28 / 2)];
    [showView addSubview:BackConsumptionStatisticsTitle];
    
    
    /** 消费统计总额*/
    UITextField * BackConsumptionStatisticsField = [[UITextField alloc] initWithFrame:CGRectMake(showView.width / 2 , BackConsumptionStatisticsTitle.y, showView.width / 2 - 40 * px, BackConsumptionStatisticsTitle.height)];
    BackConsumptionStatisticsField.textColor = [UIColor blackColor];
//    BackConsumptionStatisticsLabel.text = @"xxxx";
    BackConsumptionStatisticsField.placeholder = @"请输入收入名称";
    BackConsumptionStatisticsField.textAlignment = NSTextAlignmentRight;
    BackConsumptionStatisticsField.font = BackConsumptionStatisticsTitle.font;
    [showView addSubview:BackConsumptionStatisticsField];
    self.BackConsumptionStatisticsField = BackConsumptionStatisticsField;
    
    UIView * ConsumptionLineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(BackConsumptionStatisticsField.frame) + 30 * px, showView.width, 1)];
    ConsumptionLineView.backgroundColor = DividinglineColor;
    [showView addSubview:ConsumptionLineView];
    
    
    /** 消费统计总额*/
    UILabel * TotalConsumptionTitle = [[UILabel alloc] initWithFrame:CGRectMake(BackConsumptionStatisticsTitle.x, CGRectGetMaxY(ConsumptionLineView.frame) + 30 * px, BackConsumptionStatisticsTitle.width, BackConsumptionStatisticsTitle.height)];
    TotalConsumptionTitle.textColor = BackConsumptionStatisticsTitle.textColor;
    TotalConsumptionTitle.text = @"收入金额";
    TotalConsumptionTitle.textAlignment = BackConsumptionStatisticsTitle.textAlignment;
    TotalConsumptionTitle.font = BackConsumptionStatisticsTitle.font;
    [showView addSubview:TotalConsumptionTitle];
    
    
    
    /** 消费统计总额*/
    UITextField * TotalConsumptionField = [[UITextField alloc] initWithFrame:CGRectMake(BackConsumptionStatisticsField.x, TotalConsumptionTitle.y, BackConsumptionStatisticsField.width, BackConsumptionStatisticsField.height)];
    TotalConsumptionField.textColor = FontColor;
//    TotalConsumptionField.text = @"￥9300";
    TotalConsumptionField.keyboardType = UIKeyboardTypeNumberPad;
    TotalConsumptionField.placeholder = @"请输入收入名称";
    TotalConsumptionField.textAlignment = BackConsumptionStatisticsField.textAlignment;
    TotalConsumptionField.font = BackConsumptionStatisticsTitle.font;
    [showView addSubview:TotalConsumptionField];
    self.TotalConsumptionField = TotalConsumptionField;
    
    UIView * TotalConsumptionLineView = [[UIView alloc] initWithFrame:CGRectMake(ConsumptionLineView.x, CGRectGetMaxY(TotalConsumptionTitle.frame) + 30 * px, ConsumptionLineView.width, ConsumptionLineView.height)];
    TotalConsumptionLineView.backgroundColor = DividinglineColor;
    [showView addSubview:TotalConsumptionLineView];
    
    
    /** 结算方式*/
    UILabel * SettlementMethodLabel = [[UILabel alloc] initWithFrame:CGRectMake(BackConsumptionStatisticsTitle.x, CGRectGetMaxY(TotalConsumptionLineView.frame) + 30 * px, 200 * px, BackConsumptionStatisticsTitle.height)];
    SettlementMethodLabel.textColor = BackConsumptionStatisticsTitle.textColor;
    SettlementMethodLabel.text = @"收入方式";
    SettlementMethodLabel.textAlignment = BackConsumptionStatisticsTitle.textAlignment;
    SettlementMethodLabel.font = BackConsumptionStatisticsTitle.font;
    [showView addSubview:SettlementMethodLabel];
    
    UIView * MethodView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(SettlementMethodLabel.frame) + 20 * px, SettlementMethodLabel.y, ConsumptionLineView.width - SettlementMethodLabel.x - SettlementMethodLabel.width - 60 * px, showView.height - SettlementMethodLabel.y - 300 * px)];
    MethodView.backgroundColor = [UIColor clearColor];
    [showView addSubview:MethodView];
    
    
    NSArray * NormolIMG = @[@"筛选-未选中",@"筛选-未选中",@"筛选-未选中",@"筛选-未选中",@"筛选-未选中"];
    
    NSArray * SelectIMG = @[@"勾",@"勾",@"勾",@"勾",@"勾"];
    
    NSArray * SelectTitle = @[@"微信",@"刷卡",@"会员卡支付",@"支付宝",@"现金"];
    
    
    CGFloat selectionButtonX = 0;
    CGFloat selectionButtonH = (MethodView.height - 200 * px) / NormolIMG.count;
    CGFloat selectionButtonW = 350 * px;
    for (int i = 0; i < NormolIMG.count; i ++) {
        MSSelectionButton * selectionButton = [[MSSelectionButton alloc] init];
        selectionButton.frame = CGRectMake(selectionButtonX, (selectionButtonH + 40 * px) * i, selectionButtonW, selectionButtonH);
        selectionButton.tag = i + 1;
        [selectionButton setTitle:SelectTitle[i] forState:UIControlStateNormal];
        [selectionButton setImage:[UIImage imageNamed:NormolIMG[i]] forState:UIControlStateNormal];
        [selectionButton setImage:[UIImage imageNamed:SelectIMG[i]] forState:UIControlStateDisabled];
        [selectionButton addTarget:self action:@selector(selectionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        selectionButton.titleLabel.font = [UIFont systemFontOfSize:SYRealValue(28 / 2)];
        [selectionButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        selectionButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        
        [MethodView addSubview:selectionButton];
        if (i == 0) {
            [self selectionButtonClick:selectionButton];
            selectionButton.enabled = NO;
            
            self.selectedButton = selectionButton;
        }
        
    }
    UIButton * completeButton = [[UIButton alloc] initWithFrame:CGRectMake(30 * px, CGRectGetMaxY(MethodView.frame) + 80 * px, showView.width - 60 * px, 120 * px)];
    [completeButton setTitle:@"确认" forState:UIControlStateNormal];
    completeButton.layer.cornerRadius = 60 * px;
    completeButton.layer.masksToBounds = YES;
    completeButton.titleLabel.font = [UIFont systemFontOfSize:SYRealValue(28 / 2)];
    [completeButton setBackgroundImage:[UIImage imageNamed:@"底部按钮背景"] forState:UIControlStateNormal];
    [completeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [completeButton addTarget:self action:@selector(completeButtonClick) forControlEvents:UIControlEventTouchUpInside];
    //    [completeButton addTarget:self action:@selector(playCardButton) forControlEvents:UIControlEventTouchUpInside];
    [showView addSubview:completeButton];
}

- (void)selectionButtonClick:(UIButton *)sender{
    
//    sender.selected = !sender.selected;
    //修改按钮状态
    self.selectedButton.enabled = YES;
    sender.enabled = NO;
    self.selectedButton = sender;
    
    
}
-(void)choseButtonClick
{
    [self.backView removeFromSuperview];
}
- (void)completeButtonClick{
    [MBManager showLoading];
    NSString *incomeNameStr = [self.BackConsumptionStatisticsField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *incomeMoneyStr = [self.TotalConsumptionField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSString * incomeModelStr = [NSString stringWithFormat:@"%ld",(long)self.selectedButton.tag];
    NSDictionary * params = @{@"busId":[WYCAccountTool unarchivebelongBusid],@"projectName":incomeNameStr,@"incomeMoney":incomeMoneyStr,@"incomeMode":incomeModelStr};
    WYCLog(@"---------%@",params);
    [HTTPRequest POST:MSsaveIncome params:params succeed:^(id responseObject) {
        WYCLog(@"---------%@",responseObject);
        if (CodeStr) {
            [MBManager hideAlert];
            [MBManager showBriefAlert:responseObject[@"msg"]];
            [self.backView removeFromSuperview];
            [self ReloadData];
            
        }else{
            [MBManager hideAlert];
            [MBManager showBriefAlert:responseObject[@"msg"]];
            [self.backView removeFromSuperview];
        }
    } failure:^(NSError *error) {
        [MBManager hideAlert];
        [self.backView removeFromSuperview];
        [MBManager showBriefAlert:Failed];
    }];
//
}
@end
